//
//  ZZButtonSegView.m
//  ZuZuBao
//
//  Created by Felix on 2024/4/17.
//

#import "ZZButtonSegView.h"

@interface ZZButtonSegView ()

@property (nonatomic, strong) NSArray * array;

@end

@implementation ZZButtonSegView

-(void)setZZButtonSegWithArray:(NSArray *)array
{
    self.array = array;
    CGFloat width = (self.frame.size.width - (array.count - 1) * 10) / array.count;
    for (int i = 0; i < array.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(width * i + 10 * i, 0, width, self.frame.size.height);
        button.backgroundColor = [UIColor whiteColor];
        button.layer.cornerRadius = self.frame.size.height / 2;
        button.layer.masksToBounds = YES;
        [button setBackgroundImage:nil forState:UIControlStateNormal];
        [button setTitleColor:k999Color forState:UIControlStateNormal];
        [button setTitle:array[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.titleLabel.adjustsFontSizeToFitWidth = YES;
        button.tag = 1000 + i;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        
        if (i == 0) {
            [button setBackgroundImage:[UIImage imageNamed:@"button_back_image"] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
}

-(void)buttonAction:(UIButton *)button {
    for (int i = 0; i < self.array.count; i++) {
        UIButton * btn = [self viewWithTag:1000 + i];
        [btn setBackgroundImage:nil forState:UIControlStateNormal];
        [btn setTitleColor:k999Color forState:UIControlStateNormal];
    }
    [button setBackgroundImage:[UIImage imageNamed:@"button_back_image"] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    // 代理 点击事件
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickToButtonSeg:)]) {
        [self.delegate clickToButtonSeg:button.tag - 1000];
    }
}

-(void)setSelectIndex:(NSInteger)index {
    for (int i = 0; i < self.array.count; i++) {
        UIButton * btn = [self viewWithTag:1000 + i];
        [btn setBackgroundImage:nil forState:UIControlStateNormal];
        [btn setTitleColor:k999Color forState:UIControlStateNormal];
    }
    UIButton * button = [self viewWithTag:1000 + index];
    [button setBackgroundImage:[UIImage imageNamed:@"button_back_image"] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}

@end
